<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;

use App\Service\BotsService;
use App\Model\BotsModel;
use App\Jobs\LoginRobotJob;
use Exception;

class CheckRobot extends Command
{
	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $signature = 'check:robot {--bot_id=}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = '巡检机器人状态.';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * 获取最早登录机器人
	 * @param  int $botId 机器人ID
	 * @return array
	 */
	protected function getBotsByEarlyLogin($botId = NULL)
	{
		return BotsModel::getBotsByEarlyLogin($botId);
	}

	/**
	 * 修改机器人登录状态
	 * @param  int $botId 机器人ID
	 * @return array
	 */
	protected function updateBotsLoginState($botId)
	{
		return BotsModel::updateBotsLoginState($botId);
	}

	/**
	 * 修改机器人登录时间
	 * @param  int $botId 机器人ID
	 * @return bool
	 */
	protected function updateLastLoginTime($botId)
	{
		return BotsModel::updateLastLoginTime($botId);
	}

	protected function checkRobot()
	{
		$info = $this->getBotsByEarlyLogin($this->botId);
		if (!$info) {
			echo 'query bot info failed, botid: '.$this->botId."\r\n";
			return false;
		}

		$steam = BotsService::getInstance()->getLgoinObjByBotId($info['bot_id'], $info['steam_account']);
		if (!$steam) {
			$this->retryLogin($info['bot_id'], $info['client_no']);
			echo 'query steam failed, botid: '.$info['bot_id']."\r\n";
			return false;
		}

		$res = $this->isLogged($steam);
		if ($res == false) {
			$this->retryLogin($info['bot_id'], $info['client_no']);
			echo 'login robot waiting ...'."\r\n";
			return true;
		}
		
		$this->updateLastLoginTime($info['bot_id']);
		echo 'login robot success'."\r\n";
		return true;
	}

	private function retryLogin($botId, $clientNo)
	{
		$this->updateBotsLoginState($botId);

		dispatch((new LoginRobotJob($botId))->onQueue(($clientNo ? 'LoginRobotJob_'.$clientNo : 'LoginRobotJob'))->delay(1));
		return true;
	}

	private function isLogged($steam)
	{

		$response = $steam->cURL('https://steamcommunity.com/');
		$pattern = '/g_steamID = (.*);/';

		preg_match($pattern, $response, $matches);
		if (!isset($matches[1])) {
			return false;
		}

		$steamId = str_replace('"', '', $matches[1]);
		if ($steamId == 'false') {
			return false;
		}
		return true;
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle()
	{
		$this->botId = $this->option('bot_id');

		$this->checkRobot();
		echo '数据查询完毕!'."\r\n";
		return true;
	}
}